package leetcode.day;

// 917. 仅仅反转字母
public class ReverseOnlyLetters {

    public static void main(String[] args) {
        System.out.println(reverseOnlyLetters("7_28]"));
    }

    public static String reverseOnlyLetters(String s) {
        int p = 0;
        int q = s.length() - 1;
        char[] chars = s.toCharArray();
        while (p < q) {
            if (Character.isLetter(chars[p]) &&
                    Character.isLetter(chars[q])) {
                char tmp = chars[p];
                chars[p] = chars[q];
                chars[q] = tmp;
                p++;
                q--;
            } else if (Character.isLetter(chars[p]) && !Character.isLetter(chars[q])) {
                q--;
            } else if (!Character.isLetter(chars[p]) && Character.isLetter(chars[q])) {
                p++;
            } else {
                p++;
                q--;
            }
        }
        return String.valueOf(chars);
    }


    public static String reverseOnlyLetters2(String s) {
        int p = 0;
        int q = s.length() - 1;
        char[] chars = s.toCharArray();
        while (p < q) {
            while (p < q && !Character.isLetter(chars[p])) {
                p++;
            }
            while (p < q && !Character.isLetter(chars[q])) {
                q--;
            }
            swap(chars, p, q);
            p++;
            q--;
        }
        return new String(chars);
    }

    private static void swap(char[] chars, int p, int q) {
        char tmp = chars[p];
        chars[p] = chars[q];
        chars[q] = tmp;
    }

}
